//
//  JZPickerView.m
//  NHBaseUIFrameWork
//
//  Created by 刘星辰 on 2018/1/30.
//  Copyright © 2018年 刘星辰. All rights reserved.
//

#define ZHToobarHeight 40
#define PickViewHeight 250
#define ButtonSpace 10

#import "JZPickerView.h"
#import "Masonry.h"
#import "LGColor.h"
#import "UIViewExt.h"

@interface JZPickerView()<UIPickerViewDelegate,UIPickerViewDataSource,UIGestureRecognizerDelegate>
{
    UILabel *_centerLabel;
    UIButton * _leftBtn;
    UIButton * _rightBtn;
    BOOL _isArea;
    NSDictionary *_areaDict;
}
@property(nonatomic,copy)NSString *plistName;
@property(nonatomic,strong)NSArray *plistArray;
@property(nonatomic,assign)BOOL isLevelArray;
@property(nonatomic,assign)BOOL isLevelString;
@property(nonatomic,assign)BOOL isLevelDic;
@property(nonatomic,strong)NSDictionary *levelTwoDic;
@property(nonatomic,strong)UIView *toolbar;
@property(nonatomic,assign)NSDate *defaulDate;
@property(nonatomic,assign)BOOL isHaveNavControler;
@property(nonatomic,assign)NSInteger pickeviewHeight;
@property(nonatomic,copy)NSString *resultString;
@property(nonatomic,strong)NSMutableArray *componentArray;
@property(nonatomic,strong)NSMutableArray *dicKeyArray;
@property(nonatomic,copy)NSMutableArray *state;
@property(nonatomic,copy)NSMutableArray *city;
@end

@implementation JZPickerView

-(NSArray *)plistArray{
    if (_plistArray==nil) {
        _plistArray=[[NSArray alloc] init];
    }
    return _plistArray;
}

-(NSArray *)componentArray{
    
    if (_componentArray==nil) {
        _componentArray=[[NSMutableArray alloc] init];
    }
    return _componentArray;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //        [self setUpToolBar];
        //        self.toolbar;
        [self initialUI];
    }
    return self;
}

- (void)initialUI
{
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    
    //点击背景消失
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(remove)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
}

- (void)drawRect:(CGRect)rect
{
    
}

-(instancetype)initPickviewWithPlistName:(NSString *)plistName{
    
    self=[super init];
    if (self) {
        _plistName=plistName;
        self.plistArray=[self getPlistArrayByplistName:plistName];
        [self setUpPickView];
        
    }
    return self;
}
-(instancetype)initPickviewWithArray:(NSArray *)array{
    self=[super init];
    if (self) {
        self.plistArray=array;
        [self setArrayClass:array];
        [self setUpPickView];
        
    }
    return self;
}

-(instancetype)initDatePickWithDate:(NSDate *)defaulDate datePickerMode:(UIDatePickerMode)datePickerMode{
    
    self=[super init];
    if (self) {
        _defaulDate = (defaulDate == nil)?([NSDate date]):(defaulDate);
        [self setUpDatePickerWithdatePickerMode:(UIDatePickerMode)datePickerMode];
    }
    return self;
}

+ (instancetype)showAreaPicker
{
    return [[self alloc] initShowAreaPicker];
}
- (instancetype)initShowAreaPicker
{
    self=[super init];
    if (self) {
        
        _isArea = YES;
        NSString *path= [[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"];
        _areaDict = [NSDictionary dictionaryWithContentsOfFile:path];
        [self setUpPickView];
    }
    return self;
}

-(NSArray *)getPlistArrayByplistName:(NSString *)plistName{
    NSString *path= [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    NSArray * array= [NSArray arrayWithContentsOfFile:path];
    [self setArrayClass:array];
    return array;
}

-(void)setArrayClass:(NSArray *)array{
    _dicKeyArray=[[NSMutableArray alloc] init];
    for (id levelTwo in array) {
        
        if ([levelTwo isKindOfClass:[NSArray class]]) {
            _isLevelArray=YES;
            _isLevelString=NO;
            _isLevelDic=NO;
        }else if ([levelTwo isKindOfClass:[NSString class]]){
            _isLevelString=YES;
            _isLevelArray=NO;
            _isLevelDic=NO;
            
        }else if ([levelTwo isKindOfClass:[NSDictionary class]])
        {
            _isLevelDic=YES;
            _isLevelString=NO;
            _isLevelArray=NO;
            _levelTwoDic=levelTwo;
            [_dicKeyArray addObject:[_levelTwoDic allKeys] ];
        }
    }
}
-(void)setUpPickView{
    
    UIPickerView *pickView=[[UIPickerView alloc] init];
    pickView.backgroundColor = WHITE_COLOR;
    _pickerView=pickView;
    pickView.delegate=self;
    pickView.dataSource=self;
    
    
    [self addSubview:pickView];
    [self updatePickConstraintWith:pickView];
    
}

-(void)setUpDatePickerWithdatePickerMode:(UIDatePickerMode)datePickerMode{
    UIDatePicker *datePicker=[[UIDatePicker alloc] init];
    //    datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [datePicker setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_Hans_CN"]];
    datePicker.backgroundColor = WHITE_COLOR;
    datePicker.datePickerMode = datePickerMode;
    datePicker.backgroundColor= WHITE_COLOR;
    if (_defaulDate) {
        [datePicker setDate:_defaulDate];
    }
    _datePicker=datePicker;
    [self addSubview:datePicker];
    [self updatePickConstraintWith:datePicker];
}

#pragma mark piackView 数据源方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    NSInteger component = 0;
    
    if (_isArea)
    {
        return 3;
    }
    if (_isLevelArray) {
        component=_plistArray.count;
    } else if (_isLevelString){
        component=1;
    }else if(_isLevelDic){
        component=[_levelTwoDic allKeys].count*2;
    }
    return component;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (_isArea)
    {
        if (component == 0)
        {
            return _areaDict.allKeys.count;
        }
        else if(component == 1)
        {
            NSInteger selectIndex = [pickerView selectedRowInComponent:0];
            NSString *key = _areaDict.allKeys[selectIndex];
            NSDictionary *dict = [_areaDict[key] firstObject];
            return dict.allKeys.count;
        }
        else
        {
            NSInteger select0Index = [pickerView selectedRowInComponent:0];
            NSInteger select1Index = [pickerView selectedRowInComponent:1];
            NSString *twoKey = _areaDict.allKeys[select0Index];
            NSDictionary *dict = [_areaDict[twoKey] firstObject];
            NSString *threeKey = dict.allKeys[select1Index];
            NSArray *arr = dict[threeKey];
            return arr.count;
        }
    }
    
    NSArray *rowArray=[[NSArray alloc] init];
    if (_isLevelArray) {
        rowArray=_plistArray[component];
    }else if (_isLevelString){
        rowArray=_plistArray;
    }else if (_isLevelDic){
        NSInteger pIndex = [pickerView selectedRowInComponent:0];
        NSDictionary *dic=_plistArray[pIndex];
        for (id dicValue in [dic allValues]) {
            if ([dicValue isKindOfClass:[NSArray class]]) {
                if (component%2==1) {
                    rowArray=dicValue;
                }else{
                    rowArray=_plistArray;
                }
            }
        }
    }
    return rowArray.count;
}

#pragma mark UIPickerViewdelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (_isArea)
    {
        if (component == 0)
        {
            return _areaDict.allKeys[row];
        }
        else if(component == 1)
        {
            NSInteger selectIndex = [pickerView selectedRowInComponent:0];
            NSString *key = _areaDict.allKeys[selectIndex];
            NSDictionary *dict = [_areaDict[key] firstObject];
            return dict.allKeys[row];
        }
        else
        {
            NSInteger select0Index = [pickerView selectedRowInComponent:0];
            NSInteger select1Index = [pickerView selectedRowInComponent:1];
            NSString *twoKey = _areaDict.allKeys[select0Index];
            NSDictionary *dict = [_areaDict[twoKey] firstObject];
            NSString *threeKey = dict.allKeys[select1Index];
            NSArray *arr = dict[threeKey];
            //            NSLog(@"arr: - %@,index - %lu",arr,[pickerView selectedRowInComponent:2]);
            return arr[row];
        }
    }
    
    NSString *rowTitle=nil;
    if (_isLevelArray) {
        rowTitle=_plistArray[component][row];
    }else if (_isLevelString){
        rowTitle=_plistArray[row];
    }else if (_isLevelDic){
        NSInteger pIndex = [pickerView selectedRowInComponent:0];
        NSDictionary *dic=_plistArray[pIndex];
        if(component%2==0)
        {
            rowTitle=_dicKeyArray[row][component];
        }
        for (id aa in [dic allValues]) {
            if ([aa isKindOfClass:[NSArray class]]&&component%2==1){
                NSArray *bb=aa;
                if (bb.count>row) {
                    rowTitle=aa[row];
                }
                
            }
        }
    }
    return rowTitle;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (_isArea)
    {
        if (component == 0) {
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView reloadComponent:1];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            [pickerView reloadComponent:2];
        }else if (component == 1){
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
        return;
    }
    
    if (_isLevelDic&&component%2==0) {
        
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:YES];
    }
    if (_isLevelString) {
        _resultString=_plistArray[row];
        
    }else if (_isLevelArray){
        _resultString=@"";
        if (![self.componentArray containsObject:@(component)]) {
            [self.componentArray addObject:@(component)];
        }
        for (int i=0; i<_plistArray.count;i++) {
            if ([self.componentArray containsObject:@(i)]) {
                NSInteger cIndex = [pickerView selectedRowInComponent:i];
                _resultString=[NSString stringWithFormat:@"%@:%@",_resultString,_plistArray[i][cIndex]];
            }else{
                _resultString=[NSString stringWithFormat:@"%@:%@",_resultString,_plistArray[i][0]];
            }
        }
    }else if (_isLevelDic){
        if (component==0) {
            _state =_dicKeyArray[row][0];
        }else{
            NSInteger cIndex = [pickerView selectedRowInComponent:0];
            NSDictionary *dicValueDic=_plistArray[cIndex];
            NSArray *dicValueArray=[dicValueDic allValues][0];
            if (dicValueArray.count>row) {
                _city =dicValueArray[row];
            }
        }
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    if (_isArea)
    {
        UILabel* pickerLabel = (UILabel*)view;
        if (!pickerLabel){
            pickerLabel = [[UILabel alloc] init];
            pickerLabel.adjustsFontSizeToFitWidth = YES;
            [pickerLabel setTextAlignment:NSTextAlignmentCenter];
            [pickerLabel setBackgroundColor:[UIColor clearColor]];
            [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
        }
        // Fill the label text here
        pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
        return pickerLabel;
    }
    else
    {
        return view;
    }
}

-(void)remove{
    if ([self.delegate respondsToSelector:@selector(toobarDonCancelClick:)]) {
        [self.delegate toobarDonCancelClick:self];
    }
    [self removeFromSuperview];
}
-(void)showOn:(UIViewController *)superView
{
    [superView.view addSubview:self];
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [self bringSubviewToFront:_toolbar];
    if(_selectIndex)
    {
        [_pickerView selectRow:_selectIndex inComponent:0 animated:NO];
    }
    
}
-(void)doneClick
{
    if (_pickerView)
    {
        if (_isArea)
        {
            if ([self.delegate respondsToSelector:@selector(toobarDonBtnHaveClick:areaInfo:)])
            {
                NSInteger select0Index = [_pickerView selectedRowInComponent:0];
                NSInteger select1Index = [_pickerView selectedRowInComponent:1];
                NSInteger select2Index = [_pickerView selectedRowInComponent:2];
                NSString *twoKey = _areaDict.allKeys[select0Index];
                NSDictionary *dict = [_areaDict[twoKey] firstObject];
                NSString *threeKey = dict.allKeys[select1Index];
                NSArray *arr = dict[threeKey];
                [self.delegate toobarDonBtnHaveClick:self areaInfo:@[twoKey,threeKey,arr[select2Index]]];
            }
        }
        
        
        if (_resultString)
        {
            
        }
        else
        {
            if (_isLevelString)
            {
                _resultString=[NSString stringWithFormat:@"%@",_plistArray[self.selectIndex]];
            }
            else if (_isLevelArray)
            {
                _resultString=@"";
                for (int i=0; i<_plistArray.count;i++) {
                    _resultString=[NSString stringWithFormat:@"%@%@",_resultString,_plistArray[i][self.selectIndex]];
                }
            }
            else if (_isLevelDic)
            {
                
                if (_state==nil)
                {
                    _state =_dicKeyArray[0][0];
                    NSDictionary *dicValueDic=_plistArray[0];
                    _city=[dicValueDic allValues][0][0];
                }
                if (_city==nil)
                {
                    NSInteger cIndex = [_pickerView selectedRowInComponent:0];
                    NSDictionary *dicValueDic=_plistArray[cIndex];
                    _city=[dicValueDic allValues][0][0];
                    
                }
                _resultString=[NSString stringWithFormat:@"%@-%@",_state,_city];
            }
        }
    }else if (_datePicker)
    {
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        _resultString= [dateformatter stringFromDate:_datePicker.date];
    }
    if ([self.delegate respondsToSelector:@selector(toobarDonBtnHaveClick:resultString:)])
    {
        [self.delegate toobarDonBtnHaveClick:self resultString:_resultString];
    }
    if ([self.delegate respondsToSelector:@selector(toobarDonBtnHaveClick:selectIndex:)])
    {
        NSInteger index = [_pickerView selectedRowInComponent:0];
        [self.delegate toobarDonBtnHaveClick:self selectIndex:index];
    }
    [self removeFromSuperview];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:gestureRecognizer.view];
    
    if (CGRectContainsPoint(self.toolbar.frame, point))
    {
        return NO;
    }
    return YES;
    
}


-(UIView *)toolbar{
    if (!_toolbar)
    {
        UIView *toolbar=[[UIView alloc] init];
        toolbar.backgroundColor = BACKGROUND_COLOR;
        
        _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_leftBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_leftBtn setTitleColor:TEXT_COLOR_1 forState:UIControlStateNormal];
        _leftBtn.titleLabel.font = FONT(15);
        [_leftBtn addTarget:self action:@selector(remove) forControlEvents:UIControlEventTouchUpInside];
        [_leftBtn sizeToFit];
        [toolbar addSubview:_leftBtn];
        
        
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBtn.titleLabel.font = FONT(15);
        [_rightBtn setTitleColor:TEXT_COLOR_1 forState:UIControlStateNormal];
        [_rightBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_rightBtn addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
        [_rightBtn sizeToFit];
        [toolbar addSubview:_rightBtn];
        
        
        _centerLabel = [[UILabel alloc] init];
        _centerLabel.font = FONT(15);
        _centerLabel.textAlignment = NSTextAlignmentCenter;
        _centerLabel.textColor = TOPCAIL_COLOR;
        _centerLabel.text = @" ";
        [toolbar addSubview:_centerLabel];
        
        
        _toolbar = toolbar;
        [self addSubview:toolbar];
        
        [_leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.offset(0);
            make.width.offset(_leftBtn.width + 30);
        }];
        
        [_rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.bottom.offset(0);
            make.width.offset(_rightBtn.width + 30);
        }];
        
        [_centerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.and.centerY.equalTo(toolbar);
        }];
    }
    return _toolbar;
}

- (void)updatePickConstraintWith:(UIView *)picker
{
    [picker mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.equalTo(self.mas_bottom).offset(0);
        make.height.offset(picker.height);
    }];
    
    [self.toolbar mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(ZHToobarHeight);
        make.bottom.equalTo(picker.mas_top).offset(0);
    }];
    
}

/**
 *  设置PickView的颜色
 */
-(void)makePickViewColer:(UIColor *)color
{
    if (_pickerView != nil)
    {
        _pickerView.backgroundColor = color;
    }
    else if(_datePicker != nil)
    {
        _datePicker.backgroundColor = color;
    }
}

/**
 *  设置toobar的文字颜色
 */
-(void)makeTooltextColor:(UIColor *)color
{
//    [_leftBtn setTitleColor:color forState:UIControlStateNormal];
    [_rightBtn setTitleColor:color forState:UIControlStateNormal];
}

/**
 *  设置toobar的背景颜色
 */
-(void)makeToolbarBgColor:(UIColor *)color
{
    self.toolbar.backgroundColor = color;
}


/**
 *  设置centerLabel的字体颜色
 */

- (void)makrCenterLabelTextColor:(UIColor *)color
{
    _centerLabel.textColor = color;
}

/**
 *  设置toobar的右按钮文字
 */
- (void)makeToolbarRightBtnName:(NSString *)name
{
    [_rightBtn setTitle:name forState:UIControlStateNormal];
    [_rightBtn sizeToFit];
    [_rightBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.offset(_rightBtn.width + 30);
    }];
}

- (void)makeToolbarCenterText:(NSString *)text
{
    _centerLabel.text = text;
}
@end
